

package com.hazelcast.jet.impl.connector;

import jakarta.jms.*;

import java.util.ArrayList;
import java.util.List;

import static com.hazelcast.internal.util.ExceptionUtil.sneakyThrow;
import static com.hazelcast.test.HazelcastTestSupport.spawn;
import static jakarta.jms.Session.AUTO_ACKNOWLEDGE;
import static java.util.Collections.synchronizedList;

final class JmsTestUtil {
    private JmsTestUtil() {
    }

    static List<Object> sendMessages(ConnectionFactory cf, String destinationName, boolean isQueue, int count) throws JMSException {
        try (Connection conn = cf.createConnection(); Session session = conn.createSession(false, AUTO_ACKNOWLEDGE); MessageProducer producer = session.createProducer(isQueue ? session.createQueue(destinationName) : session.createTopic(destinationName))) {
            List<Object> res = new ArrayList<>(count);
            for (int i = 0; i < count; i++) {
                String message = "msg-" + i;
                producer.send(session.createTextMessage(message));
                res.add(message);
            }
            return res;
        }
    }

    static List<Object> consumeMessages(ConnectionFactory cf, String destinationName, boolean isQueue, int expectedCount) throws JMSException {
        Connection connection = cf.createConnection();
        connection.start();

        List<Object> messages = synchronizedList(new ArrayList<>());
        spawn(() -> {
            try (Session session = connection.createSession(false, AUTO_ACKNOWLEDGE); MessageConsumer consumer = session.createConsumer(isQueue ? session.createQueue(destinationName) : session.createTopic(destinationName))) {
                int count = 0;
                while (count < expectedCount) {
                    messages.add(((TextMessage) consumer.receive()).getText());
                    count++;
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw sneakyThrow(e);
            }
        });
        return messages;
    }
}
